"use strict";

const Controller = require("egg").Controller;
const path = require('path')
const sendToWormhole = require('stream-wormhole');
const fs = require('fs')

class FileController extends Controller {
  async list(){
    const {ctx}=this;
    const userId=ctx.getUserId();
    const files = await ctx.service.file.query({userId})
    ctx.success('查询成功',files)
  }
  async upload() {
    const { ctx, config } = this;
    const userId = ctx.getUserId();
    const stream = await ctx.getFileStream();
    const fileName = Date.now() + path.extname(stream.filename).toLocaleLowerCase();
    const uploadPath = path.join(config.baseDir, 'app/public/uploads/');
    if (!fs.existsSync(uploadPath)) fs.mkdirSync(uploadPath);
    // 文件处理，上传到云存储等等
    let filePath = path.join(uploadPath, `${fileName}`);
    const result = await new Promise((resolve, reject) => {
      const remoteFileStream = fs.createWriteStream(filePath);
      stream.pipe(remoteFileStream);
      let errFlag;
      remoteFileStream.on('error', err => {
        errFlag = true;
        sendToWormhole(stream);
        remoteFileStream.destroy();
        reject(err);
      });

      remoteFileStream.on('finish', async () => {
        if (errFlag) return;
        var stats = fs.statSync(filePath);
        resolve({ fileName, filePath, fileSize: stats.size, userId, ...stream });
      });
    });
    // return result;
    const fileInfo = await ctx.service.file.save(result)
    ctx.success('添加成功', fileInfo)
  }

}

module.exports = FileController;